//
//  EvaluteViewController.m
//  AnimationRecommend
//
//  Created by ljm on 2017/2/17.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "EvaluteViewController.h"
#import "CustomImageCell.h"
#import "DetailVC.h"
#import "ManPingModel.h"
#import <WebKit/WebKit.h>

@interface EvaluteViewController ()
                    <
                    UITableViewDelegate ,
                    UITableViewDataSource,
                    DZNEmptyDataSetSource,
                    DZNEmptyDataSetDelegate
                    >

@property (nonatomic, strong) NSMutableArray *sourceArr;
@property (nonatomic, strong) UITableView *mainTable;
@property(nonatomic,assign)CGFloat historyY;
@property (nonatomic, getter=isLoading) BOOL loading;


@end

@implementation EvaluteViewController {
    int _pageCount;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    _pageCount = 0;
    [self loadData];
    [self.view addSubview:self.mainTable];
    
}
- (void) loadData
{
    __weak typeof(self) weakSelf = self;
    self.mainTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
          // 加载网络数据
        [weakSelf requestData];
            }];
    [self.mainTable.mj_header beginRefreshing];
    
    //上拉加载更多
    self.mainTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageCount += 1;
        NSString *page = [NSString stringWithFormat:@"%d",_pageCount];
        NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",ManPingUrlStr_1,page,ManPingUrlStr_2];
        
        dispatch_queue_t queue = dispatch_get_main_queue();
        
        dispatch_async(queue, ^{
           //请求数据
            [[NetworkTools shareTools] requestWithMethod:GET andURL:urlStr andParameters:nil andCallBack:^(id data, NSError *error) {
                if (error) {
                    [weakSelf.mainTable.mj_footer endRefreshing];
                }else {
                    NSDictionary *Data = data[@"data"];
                    NSArray *feed = Data[@"feed"];
                   
                    NSArray *moreData = [ManPingModel mj_objectArrayWithKeyValuesArray:feed];
                    for (ManPingModel *model in moreData) {
                        [weakSelf.sourceArr addObject:model];
                    }
                    [weakSelf.mainTable reloadData];
                    [weakSelf.mainTable.mj_footer endRefreshing];
                    if (moreData.count == 0) {
                        [weakSelf.mainTable.mj_footer endRefreshingWithNoMoreData];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            weakSelf.mainTable.mj_footer.hidden = YES;
                        });
                    }
                }
            }];
            
        });
    }];
}

- (void)requestData {
    
    __weak typeof(self) weakSelf = self;
    NSString *page = [NSString stringWithFormat:@"%d",_pageCount];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",ManPingUrlStr_1,page,ManPingUrlStr_2];
    
    [[NetworkTools shareTools] requestWithMethod:GET andURL:urlStr andParameters:nil andCallBack:^(id data, NSError *error) {
         NSLog(@"=== == = === = == \n\n %@ ====== ========== \n\n",data);
        NSDictionary *Data = data[@"data"];
        NSArray *feed = Data[@"feed"];
        
        if (!error) {
            weakSelf.sourceArr = [ManPingModel mj_objectArrayWithKeyValuesArray:feed];
            [weakSelf.mainTable reloadData];
            [weakSelf.mainTable.mj_header endRefreshing];
            weakSelf.loading = NO;
        }
        else
        {
            NSLog(@"error ========= %@",error);
            [weakSelf.mainTable.mj_header endRefreshing];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                weakSelf.loading = NO;
            });
        }
    }];
    
//    [[NetworkTools shareTools] GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        NSLog(@"%@",responseObject);
//        weakSelf.sourceArr = [ManPingModel mj_objectArrayWithKeyValuesArray:responseObject];
//        //            for (ManPingModel *model in self.sourceArr) {
//        //                NSLog(@"%@",model.title);
//        //            }
//        [weakSelf.mainTable reloadData];
//        [weakSelf.mainTable.mj_header endRefreshing];
//        weakSelf.loading = NO;
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        NSLog(@"error ========= %@",error);
//        [weakSelf.mainTable.mj_header endRefreshing];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            weakSelf.loading = NO;
//        });
//        
//    }];

}

- (void)setLoading:(BOOL)loading
{
    //    NSLog(@"loading == %d ,,,,,,-----------,,,,,self.isLoading = %d",loading,self.isLoading);
    if (self.isLoading == loading) {
        return;
    }
    _loading = loading;
    [self.mainTable reloadEmptyDataSet];
    [self requestData];
}


#pragma mark -- 设置偏移量
/**
 *  设置imageView的偏移量
 *
 */
- (void)updateImageViewCellOffset:(CustomImageCell *)cell
{
    // 获取cell的偏移量
    CGFloat cellOffset = cell.frame.origin.y - self.mainTable.contentOffset.y;
    // 获取imageView的最大偏移量
    CGFloat imgMaxHeight = [cell imageOverflowHeight];
    // 计算imageView新的偏移量
    CGFloat offset = 0.0f - imgMaxHeight * cellOffset / self.mainTable.frame.size.height;
    // 设置imageView新的偏移量
    [cell setImageOffset:CGPointMake(0.0f, offset)];
    
}

#pragma mark -- cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return AAdaption(400);
}

#pragma mark -- section of number
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark -- number of section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sourceArr.count;
}

#pragma mark -- 给cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.model = self.sourceArr[indexPath.row];
//    cell.mainImageView.image = [UIImage imageNamed:[_sourceArr objectAtIndex:indexPath.row]];
//    cell.titleLabel.text = [_sourceArr objectAtIndex:indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.clipsToBounds = YES;
    
    return cell;
}

#pragma mark -- 点击cell 发生的事
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ManPingModel *model = self.sourceArr[indexPath.row];
    NSString *url = model.link;
    NSString *newsId = model.newsId;
    DetailVC *dvc = [[DetailVC alloc] init];
    dvc.title = @"详情";
    dvc.url = url;
    dvc.newsId = newsId;
    [self.navigationController pushViewController:dvc animated:YES];
}

#pragma mark - UIScrollViewdelegate methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for (CustomImageCell *cell in self.mainTable.visibleCells) {
        [self updateImageViewCellOffset:cell];
    }
    
    CGFloat offsetY = scrollView.contentOffset.y + self.mainTable.contentInset.top;
    CGFloat panTranslationY = [scrollView.panGestureRecognizer translationInView:self.mainTable].y;
    if (offsetY > 64) {
        if (panTranslationY > 0) {
            //下滑趋势，显示
//            [self.navigationController setNavigationBarHidden:NO animated:YES];
            self.navigationController.navigationBar.hidden = NO;
            
        }else{
            //上滑趋势，隐藏
//            [self.navigationController setNavigationBarHidden:YES animated:YES];
            self.navigationController.navigationBar.hidden = YES;
        }
    }else{
//        [self.navigationController setNavigationBarHidden:NO animated:YES];
        self.navigationController.navigationBar.hidden = NO;
    }
}

#pragma mark -- 视图将要被拖拽时隐藏
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    [UIApplication sharedApplication].statusBarHidden = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (_historyY+20 < targetContentOffset -> y){
        [self setTabBarHidden:YES];
    }
    else if(_historyY-20 > targetContentOffset -> y){
        [self setTabBarHidden:NO];
        
        //主状态栏出现
//        [UIApplication sharedApplication].statusBarHidden = NO;
    }
    _historyY = targetContentOffset -> y;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    self.navigationController.navigationBar.hidden = NO;
}


#pragma mark -- 隐藏显示tabbar
- (void)setTabBarHidden:(BOOL)hidden
{
    UIView *tab = self.tabBarController.view;
    CGRect  tabRect=self.tabBarController.tabBar.frame;
    if ([tab.subviews count] < 2) {
        return;
    }
    UIView *view;
    if ([[tab.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]]) {
        view = [tab.subviews objectAtIndex:1];
    } else {
        view = [tab.subviews objectAtIndex:0];
    }
    if (hidden) {
        view.frame = tab.bounds;
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height+self.tabBarController.tabBar.frame.size.height;
    } else {
        view.frame = CGRectMake(tab.bounds.origin.x, tab.bounds.origin.y, tab.bounds.size.width, tab.bounds.size.height);
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height-self.tabBarController.tabBar.frame.size.height;
    }
    [UIView animateWithDuration:0.5f animations:^{
        self.tabBarController.tabBar.frame=tabRect;
    }completion:^(BOOL finished) {
    }];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self updateImageViewCellOffset:(CustomImageCell *)cell];
}

#pragma mark - DZNEmptyDataSetSource Methods
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    if (self.isLoading) text = @"正在重新加载.....";
    else                text = @"加载动态信息失败";
    UIFont *font = [UIFont boldSystemFontOfSize:17.0];
    UIColor *textColor = [UIColor cz_colorWithHex:0x25282b];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    if (self.isLoading) text = @"请耐心等待";
    else                text = @"服务器无数据或者网络不好哦";
    UIFont *font = [UIFont boldSystemFontOfSize:14.5];
    UIColor *textColor = [UIColor cz_colorWithHex:0x7b8994];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}

-(UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor cz_colorWithHex:0xf0f3f5];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.isLoading)
        return [UIImage imageNamed:@"loading_imgBlue_78x78"];
    else
        return [UIImage imageNamed:@"placeholder_dropbox"];
}

- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView
{
    return self.isLoading;
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    NSString *text = @"重新加载";
    if (self.isLoading)     text = @"";
    
    UIFont *font = [UIFont boldSystemFontOfSize:14.5];
    UIColor *textColor = [UIColor cz_colorWithHex:(state == UIControlStateNormal) ? 0x007ee5 : 0x48a1ea];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
    
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    self.loading = YES;
    
    
}

#pragma mark -- sourceArr getter
- (NSMutableArray *)sourceArr
{
    if (!_sourceArr) {
        _sourceArr = [NSMutableArray array];
    }
    return _sourceArr;
}

#pragma mark -- mainTable getter
- (UITableView *)mainTable
{
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        
        _mainTable.showsVerticalScrollIndicator = NO;
        
        _mainTable.delegate = self;
        
        _mainTable.dataSource = self;
        
        _mainTable.emptyDataSetSource = self;
        
        _mainTable.emptyDataSetDelegate = self;

        _mainTable.tableFooterView = [UIView new];
        
        _mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_mainTable registerClass:[CustomImageCell class] forCellReuseIdentifier:@"cell"];
    }
    return _mainTable;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
